package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type alarmType struct {
	iAlarmType store.IAlarmType
}

var AlarmType = &alarmType{
	iAlarmType: postgres.AlarmType,
}

func (a *alarmType) init() func() {
	return func() {}
}

func (a *alarmType) onEvent(*event.Data) {}

// Create 创建
func (a *alarmType) Create(ctx context.Context, in *model.AlarmTypeCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildAlarmType(in)
	_, err = a.iAlarmType.Create(ctx, c)
	return err
}

// Update 更新
func (a *alarmType) Update(ctx context.Context, in *model.AlarmTypeUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.Name != nil {
		dict["name"] = in.Name
	}

	if in.Content != nil {
		dict["content"] = in.Content
	}

	if in.Low != nil {
		dict["low"] = in.Low
	}

	if in.High != nil {
		dict["high"] = in.High
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// 获取原始code
	code := ""
	info, _ := a.Find(ctx, &model.AlarmTypeInfoRequest{Id: in.Id})
	if info != nil {
		code = info.Code
	}

	// 更新缓存
	CacheAlarmType.DeleteCache(code)

	// 更新数据库
	err := a.iAlarmType.Update(ctx, in.Id, dict)
	if err != nil {
		return err
	}
	// 更新缓存
	CacheAlarmType.DeleteCache(code)
	return nil
}

// Delete 删除
func (a *alarmType) Delete(ctx context.Context, in *model.AlarmTypeDeleteRequest) error {
	return a.iAlarmType.Delete(ctx, in.Id)
}

// List 列表查询
func (a *alarmType) List(ctx context.Context, in *model.AlarmTypeListRequest) (*model.AlarmTypeListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.AlarmType
		out   = &model.AlarmTypeListResponse{}
	)

	if total, list, err = a.iAlarmType.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.AlarmTypesEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *alarmType) Find(ctx context.Context, in *model.AlarmTypeInfoRequest) (*model.AlarmTypeInfo, error) {
	var (
		err  error
		data *entity.AlarmType
		out  = &model.AlarmTypeInfo{}
	)

	if data, err = a.iAlarmType.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.AlarmTypeEntityToDto(data)
	return out, nil
}

// buildAlarmType 构建创建数据现场
func buildAlarmType(in *model.AlarmTypeCreateRequest) *entity.AlarmType {
	// todo: check the entity is required
	return &entity.AlarmType{

		Name: in.Name,

		Content: in.Content,

		Code: in.Code,

		Low: in.Low,

		High: in.High,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
